//
//  KLBrainsController.m
//  KL
//
//  Created by mac on 15/12/20.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

#define KLBrainsKey @"347b2a49f7119623db1a83a5b6f20fe2"

#import "KLBrainsController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface KLBrainsController ()
/** 问题 */
@property (nonatomic, strong) NSArray *question;
/** 答案 */
@property (nonatomic, strong) NSArray *answer;
/** 问题的label */
@property (weak, nonatomic) IBOutlet UILabel *questionLabel;
/** 记录当前的题数 */
@property (nonatomic, assign) NSUInteger index;
/** 答案label */
@property (weak, nonatomic) IBOutlet UILabel *answerLabel;
@property (nonatomic, strong) AVAudioPlayer *player;

@end

@implementation KLBrainsController

#pragma mark - 按钮的点击事件
- (IBAction)previous:(UIButton *)sender {
    [self.player play];
    // 清楚答案区的文字
    self.answerLabel.text = @"";
    self.index = arc4random_uniform(5640);
    self.questionLabel.text = self.question[self.index];
    if (self.index == 0) {
        sender.enabled = NO;
    }
}

- (IBAction)answerButton:(UIButton *)sender {
    [self.player play];
    self.answerLabel.text = self.answer[self.index];
}

- (IBAction)nextButton:(UIButton *)sender {
    [self.player play];
    // 清楚答案区的文字
    self.answerLabel.text = @"";
    self.index = arc4random_uniform(5640);
    self.questionLabel.text = self.question[self.index];
    if (self.index == 5639) {
        sender.enabled = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.index = arc4random_uniform(5640);
    self.questionLabel.text = self.question[self.index];
    // 创建播放器
    self.player = [self loadMusic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 懒加载
- (NSArray *)question {
    if (!_question) {
        _question = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"question.plist" ofType:nil]];
    }
    return _question;
}

- (NSArray *)answer {
    if (!_answer) {
        _answer = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"answer.plist" ofType:nil]];
    }
    return _answer;
}

- (AVAudioPlayer *)loadMusic
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"music.caf" ofType:nil
                          ];
    // 1 初始化播放器需要指定音乐文件的路径
    // 2 将路径字符串转换成url，从本地读取文件，需要使用fileURL
    NSURL *url = [NSURL fileURLWithPath:filePath];
    // 3 初始化音频播放器
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    // 4 设置循环播放
    // 设置循环播放的次数
    // 循环次数=0，声音会播放一次
    // 循环次数=1，声音会播放2次
    // 循环次数小于0，会无限循环播放
    [player setNumberOfLoops:0];
    
    // 5 准备播放
    [player prepareToPlay];
    [player setVolume:0.5];
    
    return player;
}

@end
